package face.pay.wxpay.service.impl;

import face.pay.constant.TerminalType;
import face.pay.dao.*;
import face.pay.entity.*;
import face.pay.util.ResultMessage;
import face.pay.wxpay.service.IPayAuthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import weixin.popular.api.SnsAPI;
import weixin.popular.bean.sns.SnsToken;

import java.net.URLEncoder;
import java.text.MessageFormat;


@Service
@Slf4j
public class PayAuthServiceImpl implements IPayAuthService {


    @Autowired
    private StoreInfoDao storeInfoDao;



    @Autowired
    private TerminalInfoDao terminalInfoDao;


    @Autowired
    private MchPayCodeDao mchPayCodeDao;


    @Autowired
    private OemInfoDao oemInfoDao;


    @Value("${WxCallback.url}")
    private String WxCallbackUrl;


    /**
     * 获取微信授权url
     *
     * @param deviceId
     * @return
     */
    @Override
    public String getPayAuthUrl(String deviceId) {
        TerminalInfo terminalInfo = terminalInfoDao.getByDeviceId(deviceId);
        if (terminalInfo == null) {
            //二维码无效
            log.warn("获取微信授权url>>>>>>二维码的deviceId不存在在:deviceId:{}", deviceId);
            return null;
        }
        Integer oemId = terminalInfo.getOemId();
        String appId = oemInfoDao.getOemInfoById(oemId).getAppId();
        log.info("appId:{}", appId);

        String encode_url = URLEncoder.encode(WxCallbackUrl);
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state={2}&#wechat_redirect";
        String formatUrl = MessageFormat.format(url, appId, encode_url, deviceId);
        return formatUrl;
    }


    @Override
    public void wxCallback(String code, String deviceId, Model model) {

        log.info("准备获取微信授权openid>>>>>>deviceId:{}", deviceId);

        TerminalInfo terminalInfo = terminalInfoDao.getByDeviceId(deviceId);

        OemInfo oemInfo = oemInfoDao.getOemInfoById(terminalInfo.getOemId());
        StoreInfo storeInfo = this.storeInfoDao.getById(terminalInfo.getStoreId());


        String appId = oemInfo.getAppId();
        String secret = oemInfo.getSecret();
        SnsToken snsToken = SnsAPI.oauth2AccessToken(appId, secret, code);
        String openId = snsToken.getOpenid();


        model.addAttribute("deviceId", deviceId);
        model.addAttribute("openId", openId);
        model.addAttribute("storeName", storeInfo.getName());
        log.info("获取到openId:{}<<<<<<<返回页面微信支付", openId);
    }


    /**
     * 二维码绑定设备
     *
     * @param mchPayCode
     * @return
     */
    @Override
    public ResultMessage register(MchPayCode mchPayCode) {
        String deviceId = mchPayCode.getDeviceId();
        if (StringUtils.isBlank(deviceId)) {
            return ResultMessage.createFail("设备编码输入不能为空");
        }

        String upperCaseDeviceId = deviceId.toUpperCase();
        mchPayCode.setDeviceId(upperCaseDeviceId);
        MchPayCode payCodeInfo = this.mchPayCodeDao.queryMchPayCode(mchPayCode);
        if (payCodeInfo != null) {
            //防止重复提交
            return ResultMessage.createFail("设备编码已经被绑定,请不要重复提交!!!");
        }


        TerminalInfo terminalInfo = this.terminalInfoDao.getByDeviceId(upperCaseDeviceId);
        if (terminalInfo == null) {
            return ResultMessage.createFail("无效的设备编码!!!");
        }

        if (!TerminalType.QRCODE.equals(terminalInfo.getType())) {
            return ResultMessage.createFail("请绑定二维码设备编码!!!");
        }

        mchPayCode.setMchUserId(terminalInfo.getUserId());
        mchPayCode.setTerminalId(terminalInfo.getId());

        this.mchPayCodeDao.update(mchPayCode);
        log.info("二维码绑定设备成功!!! deviceId :{}  code :{}", upperCaseDeviceId, mchPayCode.getCode());
        return ResultMessage.createSuccess();
    }
}
